const baseUrl = 'https://vanves001.com';

var djax = function(config) {
  let promise = new Promise(function (resolve, reject) {
   
    // 任何请求之前先判断是否登录
    if (!wx.getStorageSync('token') && config.url !=='/wxapp/login/doLogin') {
      doLogin()
    } else {
      run()
    }
  function inArr(str,arr) {
    for (var i=0;i<arr.length;i++) {
      if (arr[i]==str) {
        return true
      }
    }
    return false
  }

  function run() {
    var filterUri = ['/wxapp/Cart/Index', '/wxapp/Cart/addEdit','/wxapp/Cart/getCartCount']
    if (!inArr(config.url, filterUri)) {
      wx.showLoading({
        title: '加载中',
      })
    }
    
    wx.request({
      url: baseUrl + config.url,
      header: {
        'X-Requested-With': 'XMLHttpRequest',
        'D-token': wx.getStorageSync('token')
      },
      data: config.data,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode !== 200) {
          resolve(false)
        } else {
          if (res.data.code==2005) {
              wx.setStorageSync('token',null)
              djax(config)
              return false
          }  
          if (res.data.code == 2003) {
            wx.reLaunch({
              url: '/pages/logs/logs'
            })
          }

          resolve(res.data)
        }
      }
    })
  }
  function doLogin() {
    wx.login({
      success: function (res) {
        djax({
          url: '/wxapp/login/doLogin',
          data: {
            code: res.code
          }
        }).then(function (res) {
          if (res.code != 1001) {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
          } else {
            wx.setStorageSync('token', res.data.token)
            wx.setStorageSync('user', res.data)
            run()
          }
        })
      }
    })
  }

    
  })
  return promise
}

module.exports = {
  djax: djax,
  baseUrl: baseUrl
}
